package com.apexsoft.monitor.front.console.task.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apexsoft.front.common.support.Result;
import com.apexsoft.monitor.common.MonitorConstant;
import com.apexsoft.monitor.common.http.HttpHelper;
import com.apexsoft.monitor.front.console.host.om.Host;
import com.apexsoft.monitor.front.console.host.service.HostService;
import com.apexsoft.monitor.front.console.task.dao.TaskDao;
import com.apexsoft.monitor.front.console.task.om.Task;
import com.apexsoft.monitor.utils.GuavaCacheHelper;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service("taskService")
public class TaskService {
    private static final Logger log = LogManager.getRootLogger();

    @Autowired
    @Qualifier("hostService")
    private HostService hostService = null;

    @Autowired
    @Qualifier("taskDao")
    private TaskDao taskDao = null;


    /**
     * 新增任务管理
     *
     * @param request
     * @return
     */
    public JSONObject add(HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String hostCode = request.getParameter("hostCode");
        String nodeCode = request.getParameter("nodeCode");
        String taskCode = UUID.randomUUID().toString();
        String taskName = request.getParameter("taskName");
        String type = request.getParameter("type");
        String value = request.getParameter("value");
        String status = request.getParameter("status");
        String attribute = request.getParameter("attribute");
        if (StringUtils.isNotBlank(taskName)
                && StringUtils.isNotBlank(nodeCode)
                && StringUtils.isNotBlank(taskName)
                && StringUtils.isNotBlank(value)
                && StringUtils.isNotBlank(type)
                && StringUtils.isNotBlank(status)
                ) {
            try {
                Host host = hostService.getByCode(hostCode);
                if(host.getHostStatus()==0){
                    result.put(Result.CODE, Result.EC_1000);
                    result.put(Result.NOTE, "新增任务失败【该中间件主机未启用】");
                    return result;
                }
                JSONObject taskJson = new JSONObject();
                taskJson.put("node_code",nodeCode);
                taskJson.put("task_code",taskCode);
                taskJson.put("task_name",taskName);
                taskJson.put("status",Integer.parseInt(status));
                taskJson.put("task_type",type);
                taskJson.put("value",value);
                taskJson.put("attr",attribute);

                JSONObject paramsJson = new JSONObject();
                paramsJson.put("task",taskJson);
                paramsJson.put("func","Task_Add");
                //设置请求头
                Map<String,String> headerMap = new HashMap<>();
                headerMap.put("HeaderToken","81CF7DDC68CDF393D3FC705050F71029");
                //获取URL
                String url = MonitorConstant.HTTP_Front + host.getHostIp()+":"+host.getAgentPort()+"/ctrl";
                //调用HttpHelper获取
                for (int i = 0; i <3 ; i++) {
                    String returnValue =(String) HttpHelper.post(url,paramsJson.toJSONString(),headerMap);
                    JSONObject resultTemp = JSONObject.parseObject(returnValue);
                    if (resultTemp.getIntValue("code")>0){
                        result.put(Result.CODE, Result.SC_0001);
                        result.put(Result.NOTE, "新增任务成功");
                        GuavaCacheHelper.remove(MonitorConstant.CACHE_KEY_NODE);
                        break;
                    }else {
                        result.put(Result.CODE, Result.EC_1000);
                        result.put(Result.NOTE, "新增任务失败");
                    }
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                log.error("新增任务管理失败：" + e.getMessage(), e);
                result.put(Result.CODE, Result.EC_1000);
                result.put(Result.NOTE, "新增任务管理失败");
            }
        } else {
            result.put(Result.CODE, Result.EC_1000);
            result.put(Result.NOTE, "参数不正确");
        }
        return result;
    }

    /**
     * 更新任务管理
     *
     * @param request
     * @return
     */
    public JSONObject update(HttpServletRequest request) {
        JSONObject result = new JSONObject();

        String hostCode = request.getParameter("hostCode");
        String nodeCode = request.getParameter("nodeCode");
        String taskCode = request.getParameter("taskCode");
        String taskName = request.getParameter("taskName");
        String type = request.getParameter("type");
        String value = request.getParameter("value");
        String status = request.getParameter("status");
        String attribute = request.getParameter("attribute");

        if (StringUtils.isNotBlank(taskName)
                && StringUtils.isNotBlank(hostCode)
                && StringUtils.isNotBlank(nodeCode)
                && StringUtils.isNotBlank(taskCode)
                && StringUtils.isNotBlank(taskName)
                && StringUtils.isNotBlank(value)
                && StringUtils.isNotBlank(type)
                && StringUtils.isNotBlank(status)
                ) {

            try {

                Host host = hostService.getByCode(hostCode);
                if(host.getHostStatus()==0){
                    result.put(Result.CODE, Result.EC_1000);
                    result.put(Result.NOTE, "任务修改失败【该中间件主机未启用】");
                    return result;
                }
                JSONObject taskJson = new JSONObject();
                taskJson.put("node_code",nodeCode);
                taskJson.put("task_code",taskCode);
                taskJson.put("task_name",taskName);
                taskJson.put("status",Integer.parseInt(status));
                taskJson.put("task_type",type);
                taskJson.put("value",value);
                taskJson.put("attr",attribute);

                JSONObject paramsJson = new JSONObject();
                paramsJson.put("task",taskJson);
                paramsJson.put("func","Task_Update");
                //设置请求头
                Map<String,String> headerMap = new HashMap<>();
                headerMap.put("HeaderToken","81CF7DDC68CDF393D3FC705050F71029");
                //获取URL
                String url = MonitorConstant.HTTP_Front + host.getHostIp()+":"+host.getAgentPort()+"/ctrl";
                //调用HttpHelper获取
                for (int i = 0; i <3 ; i++) {
                    String returnValue =(String) HttpHelper.post(url,paramsJson.toJSONString(),headerMap);
                    JSONObject resultTemp = JSONObject.parseObject(returnValue);
                    if (resultTemp.getIntValue("code")>0){
                        result.put(Result.CODE, Result.SC_0001);
                        result.put(Result.NOTE, "任务修改成功");
                        GuavaCacheHelper.remove(MonitorConstant.CACHE_KEY_NODE);
                        break;
                    }else {
                        result.put(Result.CODE, Result.EC_1000);
                        result.put(Result.NOTE, "任务修改失败");
                    }
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                log.error("任务修改失败：" + e.getMessage(), e);
                result.put(Result.CODE, Result.EC_1000);
                result.put(Result.NOTE, "任务修改失败");
            }
        }
        return result;
    }

    /**
     * 删除任务管理
     * @param hostCode
     * @param nodeCode
     * @param taskCode
     * @return
     */
    public JSONObject delete(String hostCode,String nodeCode,String taskCode) {
        JSONObject result = new JSONObject();
        if (StringUtils.isNotBlank(hostCode) && StringUtils.isNotBlank(nodeCode) && StringUtils.isNotBlank(taskCode)) {
            try {
                //获取URL
                Host host = hostService.getByCode(hostCode);
                if(host.getHostStatus()==0){
                    result.put(Result.CODE, Result.EC_1000);
                    result.put(Result.NOTE, "任务删除失败【该中间件主机未启用】");
                    return result;
                }
                JSONObject paramsJson = new JSONObject();
                paramsJson.put("task_code",taskCode);
                paramsJson.put("node_code",nodeCode);
                paramsJson.put("func","Task_Delete");
                //设置请求头
                Map<String,String> headerMap = new HashMap<>();
                headerMap.put("HeaderToken","81CF7DDC68CDF393D3FC705050F71029");

                String url = MonitorConstant.HTTP_Front + host.getHostIp()+":"+host.getAgentPort()+"/ctrl";
                //调用HttpHelper获取
                for (int i = 0; i <3 ; i++) {
                    String returnValue =(String) HttpHelper.post(url,paramsJson.toJSONString(),headerMap);
                    JSONObject resultTemp = JSONObject.parseObject(returnValue);
                    if (resultTemp.getIntValue("code")>0){
                        result.put(Result.CODE, Result.SC_0001);
                        result.put(Result.NOTE, "任务删除成功");
                        GuavaCacheHelper.remove(MonitorConstant.CACHE_KEY_NODE);
                        break;
                    }else {
                        result.put(Result.CODE, Result.EC_1000);
                        result.put(Result.NOTE, "任务删除失败");
                    }
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                log.error("任务删除失败：" + e.getMessage(), e);
                result.put(Result.CODE, Result.EC_1000);
                result.put(Result.NOTE, "任务删除失败");
            }
        }
        return result;
    }

    /**
     * 查询单条记录
     *
     * @param id
     * @return
     */
    public Task getById(int id) {
        return taskDao.selectById(id);
    }


    /**
     * 保存任务
     * @param request
     * @return
     */
    public JSONObject saveTask(HttpServletRequest request) {
        JSONObject result = new JSONObject();
        String category = request.getParameter("category");
        String category_code = request.getParameter("category_code");
        String group = request.getParameter("group");
        String selectStr = request.getParameter("selectStr");
        if(StringUtils.isNotBlank(category)
                && StringUtils.isNotBlank(category_code)
                && StringUtils.isNotBlank(group)
                ){
            try{
                //删除相关记录
                HashMap<String,Object> paramMap = new HashMap<>();
                paramMap.put("category",category);
                paramMap.put("category_code",category_code);
                paramMap.put("`group`",group);
                taskDao.deleteByMap(paramMap);
                //新增数据
                if(StringUtils.isNotBlank(selectStr)){
                    String[] taskArray = selectStr.split("\\|");
                    for(int i=0;i<taskArray.length;i++){
                        String[] taskStr = taskArray[i].split(",");
                        String taskName = taskStr[0];
                        String taskCode = taskStr[1];
                        String type     = taskStr[2];
                        String status   = taskStr[3];
                        String value    = taskStr[4];
                        Task task = new Task();
                        task.setCategoryCode(category_code);
                        task.setCategory(category);
                        task.setStatus(status);
                        task.setType(type);
                        task.setGroup(group);
                        task.setTaskName(taskName);
                        task.setTaskCode(taskCode);
                        task.setValue(value);
                        taskDao.insert(task);
                    }
                }
                result.put(Result.CODE, Result.SC_0001);
                result.put(Result.NOTE, "保存任务成功");
            }catch (Exception e) {
                log.error("保存任务失败：" + e.getMessage(), e);
                result.put(Result.CODE, Result.EC_1000);
                result.put(Result.NOTE, "保存任务失败");
            }
        }else {
            result.put(Result.CODE, Result.EC_1000);
            result.put(Result.NOTE, "参数不正确");
        }
        return result;
    }

    /**
     * 查询任务列表
     * @param
     * @return
     */
    public JSONObject getTask(HttpServletRequest request){
        JSONObject result = new JSONObject();
        String hostCode = request.getParameter("hostCode");
        String nodeCode = request.getParameter("nodeCode");
        JSONArray taskList = new JSONArray();
        try {
            JSONObject nodeObj = (JSONObject)GuavaCacheHelper.get(MonitorConstant.CACHE_KEY_NODE);
            if(nodeObj.getIntValue(Result.CODE)>0){
                JSONArray nodeArray = nodeObj.getJSONArray(Result.ROWS);
                    for (int i = 0; i <nodeArray.size() ; i++) {
                        JSONObject node = nodeArray.getJSONObject(i);
                        if(node.getString("hostCode").equals(hostCode)&&
                                node.getString("nodeCode").equals(nodeCode)){
                            taskList = node.getJSONArray("tasks");
                            if(taskList!=null & taskList.size()>0){
                                result.put(Result.CODE, Result.SC_0001);
                                result.put(Result.ROWS, taskList);
                                result.put(Result.NOTE, "任务列表获取成功");
                            }else{
                                result.put(Result.CODE, Result.EC_1000);
                                result.put(Result.NOTE, "暂无数据");
                            }
                        }
                    }
            }else{
                result.put(Result.CODE, Result.EC_1000);
                result.put(Result.NOTE, "暂无中间件数据");
            }
        }catch (Exception e) {
            log.error("任务列表获取失败：" + e.getMessage(), e);
            result.put(Result.CODE, Result.EC_1000);
            result.put(Result.NOTE, "任务列表获取失败");
        }

//        String taskName = request.getParameter("taskName");
//        String taskCode = request.getParameter("taskCode");
//        String category = request.getParameter("category");
//        String categoryCode = request.getParameter("category_code");
//        String group = request.getParameter("group");
//        String type = request.getParameter("type");
//        String status = request.getParameter("status");
//        Task task = new Task();
//        task.setTaskName(taskName);
//        task.setTaskCode(taskCode);
//        task.setCategory(category);
//        task.setCategoryCode(categoryCode);
//        task.setGroup(group);
//        task.setType(type);
//        task.setStatus(status);
//        try {
//            List<Task> list = taskDao.selectByTask(task);
//            result.put(Result.RECORDS, list);
//            result.put(Result.CODE,Result.SC_0001);
//            result.put(Result.NOTE, "任务列表获取成功");
//        }catch (Exception e) {
//            log.error("任务列表获取失败：" + e.getMessage(), e);
//            result.put(Result.CODE, Result.EC_1000);
//            result.put(Result.NOTE, "任务列表获取失败");
//        }
        return result;
    }

    /**
     * 查询任务
     * @param nodeCode
     * @return
     */
    public JSONObject queryTaskByNodeCode(String nodeCode){
        JSONObject result = new JSONObject();
        try{
            List<Task> list = taskDao.queryTaskByNodeCode(nodeCode);
            result.put(Result.ROWS,list);
            result.put(Result.CODE,Result.SC_0001);
            result.put(Result.NOTE,"成功");
        }catch (Exception e){
            result.put(Result.CODE,Result.EC_1000);
            result.put(Result.NOTE,e.getMessage());
        }
        return result;
    }
}
